//
//  ViewController4.swift
//  networkAndData
//
//  Created by 左忠飞 on 2021/1/14.
//  Copyright © 2021 左忠飞. All rights reserved.
//

import UIKit

class ViewController4: ViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //归档
        
        //获取根目录
        let homeDicPath = NSHomeDirectory()
        //创建文件完整路径
        let filePath = homeDicPath + "archiver.file"
        //将字符串数据"jaki"进行归档操作
        NSKeyedArchiver.archiveRootObject("jaki", toFile: filePath)
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //解档
        //获取根目录
        let homeDicPath = NSHomeDirectory()
        //创建文件完整路径
        let filePath = homeDicPath + "archiver.file"
        //进行解档
        let value = NSKeyedUnarchiver.unarchiveObject(withFile: filePath)
        print(value ?? "未找到数据")
        
        
        
        //归档解档自定义数据
        let xiaoming = People()
        xiaoming.name = "小明"
        xiaoming.age = 11
        
        //归档
        NSKeyedArchiver.archiveRootObject(xiaoming, toFile: homeDicPath + "xiaoming")
        
        //解档
        let xiaoming2 = NSKeyedUnarchiver.unarchiveObject(withFile: homeDicPath + "xiaoming") as! People
        print(xiaoming2.name!,xiaoming2.age)
        
    }
}

class People: NSObject,NSCoding {
    func encode(with coder: NSCoder) {
        coder.encode(age,forKey: "age")
        coder.encode(name,forKey: "name")
        
    }
    
    required init?(coder: NSCoder) {
        super.init()
        self.name = coder.decodeObject(forKey: "name") as? String
        self.age = coder.decodeInteger(forKey: "age")
    }
    
    var name:String?
    var age:NSInteger = 0
    
    override init() {
        super.init()
    }
    
}

